package com.ivy.irublesson.fragment;

import android.app.Activity;


import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import com.ivy.irublesson.GetConnection.TeacherConn;
import com.ivy.irublesson.R;
import com.ivy.irublesson.activity.TContentActivity;
import com.ivy.irublesson.adapter.TeacherAdapter;
import com.ivy.irublesson.entity.Teacher;
import com.ivy.irublesson.utils.HttpUtil;
import com.ivy.irublesson.utils.MyOpenHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/1/10.
 */

public class TeacherFragment extends Fragment implements AdapterView.OnItemClickListener ,AdapterView.OnItemLongClickListener{
    private TeacherAdapter adapter;
    private ArrayAdapter<String> adapter1;

    private Activity context;

    private ListView list_view;
    private List<Teacher> teachers = new ArrayList<>();
    private List<String> allValues = new ArrayList<>();


    private SearchView searchView;

    private Handler handler;
    private MyOpenHelper openHelper;
    //private int sid;
    public TeacherFragment(Activity context){
        this.context = context;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        final View view  = inflater.inflate(R.layout.fragment_teacher,null);
        openHelper = new MyOpenHelper(context, "irublesson.db", null, 1);

        SQLiteDatabase database = openHelper.getReadableDatabase();
        String sql = "select * from teacher";
        Cursor cursor = database.rawQuery(sql, null);	//	若是有问号，传入参数数组   否则为null；

        if( !cursor.moveToNext()) {
            //  数据库没有数据，联网获取数据，并插入数据库
            Thread teacherThread = new Thread(new TeacherThread());
            teacherThread.start();
            for(Teacher t:teachers){
                String sql1 = "insert into teacher(tname,tid,sid) values( "+t.getTname()+" , "+t.getTid()+" ,"+t.getSid()+")";
                database.execSQL(sql1);
            }

        } else{
            while(cursor.moveToNext()) {
                String  tid = cursor.getString(1);
                String tname = cursor.getString(cursor.getColumnIndex("tname"));
                int sid = cursor.getInt(cursor.getColumnIndex("sid"));
                Teacher person = new Teacher(tname , tid , sid);
                teachers.add(person);
            }

        }
        cursor.close();
        database.close();

        for(Teacher t : teachers) {
            allValues.add(t.getTid()+t.getTname());
        }

        //initTeachers();
        searchView = (SearchView) view.findViewById(R.id.searchView1);

        list_view = (ListView) view.findViewById(R.id.list_view1);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:
                        adapter = new TeacherAdapter(context , teachers);
                        list_view.setAdapter( adapter );
                        break;
                }

            }
        };      //用runonuuithread

        //  模糊查询
                        adapter1=new ArrayAdapter<String>(getContext(), android.R.layout.simple_expandable_list_item_1,allValues);
                        list_view.setAdapter(adapter1);
                        list_view.setTextFilterEnabled(true);
        // 设置搜索文本监听 setOnQueryTextListener
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // 当点击搜索按钮时触发该方法
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            // 当搜索内容改变时触发该方法 onQueryTextChange
            @Override
            public boolean onQueryTextChange(String newText) {
                if (!TextUtils.isEmpty(newText)){
                    list_view.setFilterText(newText);
                    //Toast.makeText(context, "1111", Toast.LENGTH_SHORT).show();
                }else{
                    list_view.clearTextFilter();
                    //Toast.makeText(context, "222", Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        });


        list_view.setOnItemClickListener(this);
        list_view.setOnItemLongClickListener(this);
        return view;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Teacher teacher = teachers.get(position);
        Intent intent = new Intent(context, TContentActivity.class);
        intent.putExtra("tid", teacher.getTid());
        intent.putExtra("tname", teacher.getTname());
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
    //定义AlertDialog.Builder对象，当长按列表项的时候弹出确认删除对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
        builder.setMessage("确定删除?");
        builder.setTitle("提示");

        //添加AlertDialog.Builder对象的setPositiveButton()方法
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if(teachers.remove(position)!=null){
                    System.out.println("success");
                }else {
                    System.out.println("failed");
                }
                adapter.notifyDataSetChanged();
                Toast.makeText(context, "删除列表项", Toast.LENGTH_SHORT).show();
            }
        });

        //添加AlertDialog.Builder对象的setNegativeButton()方法
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder.create().show();
        return true;
    }

//    private String listpath = "";
//    private String listcookie = "";

    private String teacherPath = "http://119.23.232.105:8080/IRubLesson/TeacherServlet";
    class TeacherThread implements Runnable {
        public void run() {

//            teachers = TeacherConn.getTeacher();

            try {
                JSONArray arr = HttpUtil.getJSONArrayByURL(teacherPath );
                for(int i = 0;i < arr.length();i++) {
                    JSONObject obj = arr.getJSONObject(i);
                    Teacher teacher = new Teacher();
                    teacher.setTname(obj.getString("tname"));
                    teacher.setTid(obj.getString("tid"));
                    teacher.setSid(obj.getInt("sid"));
                    //  map.put("owner_tel", obj.getString("owner_tel"));
                    teachers.add(teacher);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            Message msg = new Message();
            msg.what = 1;
            handler.sendMessage(msg);

        }

    }

//    private void initTeachers(){
//        for(int i = 0;i<20;i++){
//            Teacher xiao = new Teacher("1001","妖娆 ぅ");
//            teachers.add(xiao);
//
//        }
//    }

}
